package com.cqs.leetcode;

public class MedianofTwoSortedArrays {

    //
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int ml = (len1 + len2 - 1) / 2;
        int mr = (len1 + len2) / 2; // index
        int count = 0; //move times
        int p1 = 0, p2 = 0;
        int pre = 0, cur = 0;
        while (++count <= (mr + 1)) {
            pre = cur;
            if (p1 >= len1) {
                cur = nums2[mr - len1];
//                if (ml == mr) return cur;
                if (ml < mr) {
                    if (mr > len1) pre = Math.max(pre, nums2[ml - len1]);
                }
                break;

            } else if (p2 >= len2) {
                cur = nums1[mr - len2];
//                if (ml == mr) return cur;
                if (ml < mr) {
                   if (mr > len2) pre = Math.max(pre,nums1[ml - len2]);
                }
                break;
            } else {
                if (nums1[p1] < nums2[p2]) {
                    cur = nums1[p1++];
                } else {
                    cur = nums2[p2++];
                }
            }
        }
//        System.out.println(pre + "\t" + cur);
        if (ml == mr) return cur;
        return (pre + cur) / 2.0;
    }

    public static void main(String[] args) {
        MedianofTwoSortedArrays arrays = new MedianofTwoSortedArrays();
//        int[] nums1 = ArraysUtils.randInts(6);
//        int[] nums2 = ArraysUtils.randInts(6);
//        ArraysUtils.sort(nums1);
//        ArraysUtils.sort(nums2);
//        ArraysUtils.print(nums1);
//        ArraysUtils.print(nums2);-     WWW.CLKSO.NET/Z

        int[] nums1 = {1, 7};
        int[] nums2 = {3, 8,9,10};
        double result = arrays.findMedianSortedArrays(nums1, nums2);
        System.out.println(result);

        System.out.println(Integer.MAX_VALUE >>> 31);
    }

}
